<template>
  <div id="sign">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>考勤记录</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="block">
      <el-date-picker
        v-model="value2"
        align="right"
        type="month"
        placeholder="选择日期"
        format="yyyy 年 MM 月"
        value-format="yyyy/MM"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button @click="goToDate">跳转</el-button>
    </div>

    <vue-event-calendar
      :title="title"
      :events="demoEvents"
      @day-changed="handleDayChanged">
      <template slot-scope="props">
        <div v-for="(event, index) in props.showEvents" class="event-item">
          <!-- In here do whatever you want, make you owner event template -->
          <div class="wrapper">
            <el-tooltip class="item" effect="dark" :content="event.signAddress" placement="top">
              <h3 class="title"><i class="el-icon-location-information"></i>{{event.signAddress.slice(0,20)}}</h3>
            </el-tooltip>
            <p class="time">{{event.date}}</p>
            <p class="desc">签到编码： {{event.signCode}}</p>
            <p class="desc">签到说明： {{event.title}}</p>
            <p class="desc">签到时间： {{event.createTime}}</p>
          </div>
        </div>
      </template>
    </vue-event-calendar>

    <el-dialog
      title="打卡"
      v-loading="addressLoading"
      element-loading-text="获取定位中，请稍等..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :show-close="false"
      :visible="signVisible"
      width="30%"
      center>
      <el-form :model="signForm"
               :rules="rules"
               ref="signForm">
        <el-form-item label="打卡日期：" prop="ts">
          <el-input
            placeholder="请选择日期"
            suffix-icon="el-icon-date"
            v-model="signForm.ts" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="打卡地址：" prop="signAddress">
          <el-input type="text"
                    v-model="signForm.signAddress"
                    auto-complete="off"
                    placeholder="点击右侧按钮获取您的位置" disabled>
            <el-button slot="append" @click="getLocation" icon="el-icon-location-information"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="打卡说明：" prop="signRemark">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5}"
                    v-model="signForm.signRemark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="signDialogClose">取  消</el-button>
        <el-button type="primary" @click="signIn">打 卡</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import {Get, Post} from "../../api/axiosFun";
    import {timestampToDate, timestampToMonth, timestampToTime} from "../../utils/util";
    let today = new Date()
    export default {
        data() {
            return {
                signForm:{
                    ts: '',
                    signStatus: '',
                    signAddress: '',
                    signRemark: ''
                },
                //rules前端验证
                rules: {
                    signAddress: [{required: true, message: '请获取打卡地址', trigger: 'blur'}],
                    signAddress: [{required: true, message: '请获取打卡地址', trigger: 'change'}]
                },
                addressLoading: false,
                signVisible: false,

                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
                value2: `${timestampToMonth(today)}`,
                title: '',
                demoEvents: [],
            }
        },
        created() {
            this.title = `${today.getFullYear()}`+'年'+`${today.getMonth() + 1 < 10 ? '0' + (today.getMonth() + 1) : today.getMonth() + 1}` + '月考勤记录'
            this.getData({});
        },
        methods: {
            getData(params) {
                Get("/officeSystem/signIn/selectRecord", params)
                    .then(result => {
                        if (result.status == 200) {
                            result.data.forEach(item => {
                                item.date = timestampToDate(item.ts);
                                item.title = item.signRemark;
                                item.createTime = timestampToTime(item.createTime);
                            })
                            this.demoEvents = result.data;
                        } else {
                            this.demoEvents = [];
                        }
                    })
            },
            handleDayChanged(data) {
                if(data.events.length != 0){
                    this.signVisible = false;
                    return;
                }
                this.goToDate();
                let now = new Date();
                let date = new Date(data.date);
                if(now.getTime() < date.getTime()){
                    this.$message.warning("时间未到，无需打卡");
                    return;
                }
                let array = data.date.split('/')
                if(array[2] == null){
                    this.signVisible = false;
                    return
                }
                this.signForm.ts = timestampToDate(date);
                this.signForm.signStatus = 2;
                this.signVisible = true;
            },
            goToDate(){
                let date = timestampToMonth(new Date())
                //到指定日期
                if(this.value2 != null){
                    date = this.value2
                }
                let array = date.split('/')
                this.title = array[0] + '年' + array[1] + "月考勤记录";
                let params = {
                    date: date.replace('/', '-')
                }
                this.getData(params);
                this.$EventCalendar.toDate(date)
            },

            signDialogClose(done){
                this.$confirm('是否取消打卡?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.goToDate();
                    this.signVisible = false;
                }).catch(() => {
                });


            },
            //定位
            getLocation() {
                const self = this
                self.addressLoading = true;
                AMap.plugin('AMap.Geolocation', function () {
                    var geolocation = new AMap.Geolocation({
                        // 是否使用高精度定位，默认：true
                        enableHighAccuracy: true,
                        // 设置定位超时时间，默认：无穷大
                        timeout: 10000,
                    })

                    geolocation.getCurrentPosition()
                    AMap.event.addListener(geolocation, 'complete', onComplete)
                    AMap.event.addListener(geolocation, 'error', onError)

                    function onComplete(data) {
                        // data是具体的定位信息
                        console.log('获取定位成功')
                        self.signForm.signAddress = data.formattedAddress;
                        self.addressLoading = false;
                    }

                    function onError(data) {
                        // 定位出错
                        self.getLngLatLocation()
                    }
                })
            },
            getLngLatLocation() {
                const self = this
                AMap.plugin('AMap.CitySearch', function () {
                    var citySearch = new AMap.CitySearch()
                    citySearch.getLocalCity(function (status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            // 查询成功，result即为当前所在城市信息
                            self.$message.warning("获取定位失败，通过ip获取当前位置")
                            //逆向地理编码
                            AMap.plugin('AMap.Geocoder', function() {
                                var geocoder = new AMap.Geocoder({
                                    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                                    city: result.adcode
                                })

                                var lnglat = result.rectangle.split(';')[0].split(',')

                                geocoder.getAddress(lnglat, function(status, data) {
                                    if (status === 'complete' && data.info === 'OK') {
                                        // result为对应的地理位置详细信息
                                        self.signForm.signAddress = data.regeocode.formattedAddress
                                    }
                                })
                            })
                            self.addressLoading = false;
                        }else{
                            self.$message.warning("获取定位失败")
                            self.addressLoading = false;
                        }
                    })
                })
            },

            signIn(){
                this.$refs['signForm'].validate((valid) => {
                    if(valid){
                        Post("/officeSystem/signIn/insert", this.signForm)
                            .then(result=>{
                                if(result.status == 200){
                                    this.$message.success(result.message);
                                    this.goToDate();
                                    this.signVisible = false;
                                }else{
                                    this.$message.error(result.message);
                                }
                            })
                    }else{
                        return false;
                    }
                });
            },
        }
    }
</script>

<style>
  #sign {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #2c3e50;
  }

  h1, h2, h3 {
    font-weight: normal;
    margin: 0;
    padding: 0;
  }

  a {
    color: #42b983;
  }

  .t-center {
    text-align: center;
    margin: 20px;
  }

  .mt150 {
    margin-top: 150px;
  }

  .block{
    text-align: center;
    padding: 20px;
  }

  .__vev_calendar-wrapper .cal-wrapper .cal-header .r,
  .__vev_calendar-wrapper .cal-wrapper .cal-header .l {
    display: none;
  }

  .__vev_calendar-wrapper .cal-wrapper .cal-header .title{
    width: 100%;
  }
</style>
